package com.humanminoritygame.model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;


@Entity
@Table(uniqueConstraints = {@UniqueConstraint(columnNames={"userId", "roomId"})})
public class Subscription extends PersistentEntity implements Comparable<Subscription>{
	
  public enum State {
    ACTIVE, QUIT
  };

  @ManyToOne
  @JoinColumn(name="questionId")
  private Question question;
  
  @ManyToOne
  @JoinColumn(name="userId")
  private User user;

  @ManyToOne(cascade = CascadeType.ALL)
  @JoinColumn(name="roomId")
  private Room room;
  
  @Enumerated(EnumType.STRING)
  private State state;
  
  //se va actualizando cada vez que se calculan los puntos de cada ronda
  private int score;

  Subscription() {
  }
  
  public Subscription(Room room, User user, Question question) {
    super();
    this.room = room;
    this.user = user;
    this.question = question;
    this.state = State.ACTIVE;
    this.score = room.getWorstScore();
    room.addSubscription(this);
  }

  public void quit() {
    state = State.QUIT;
  }

  public User getUser(){
    return user;
  }
  
  public Room getRoom() {
    return room;
  }
  
  @Override
  public int compareTo(Subscription o) {
    int result = user.compareTo(o.getUser());
    if (result == 0) {
      result = room.compareTo(o.getRoom());
    }
    return result;
  }
  
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((room == null) ? 0 : room.hashCode());
    result = prime * result + ((user == null) ? 0 : user.hashCode());
    return result;
  }

  @Override
  public boolean equals(Object obj) {
    return super.equals(obj);
  }

  public State getState() {
    return state;
  }
  
  public Question getQuestion(){
    return question;
  }
   
  public boolean isActive(){
    return state == State.ACTIVE;
  }

  public void setScore(int score) {
    this.score = score;
  }

  public int getScore() {
    return score;
  }

  public int addScore(int points) {
    return (this.score += points);
  }
}
